package com.example.exception;

import lombok.extern.slf4j.Slf4j;

/**
 * @author audy
 * @description: TODO
 * @date 2022/7/25 23:20
 */
@Slf4j
public class ExceptionBug implements AutoCloseable{


    @Override
    public void close() throws Exception {
        throw new Exception("释放资源异常");
    }

    public void read() throws Exception{
        throw new Exception("读取失败");
    }

    public static void main(String[] args) throws Exception {
        //right2();
        ExceptionBug exceptionBug = new ExceptionBug();
        exceptionBug.right3();
    }


    /**
     * 只会抛出finally 中的异常，是因为一个方法只能抛出一个异常
     */
    public static void wrong1(){

        try {
            log.info("try 块执行");
            throw new RuntimeException("try 块抛出异常");
        } finally {
            log.info("finally");
            throw new RuntimeException("finally抛出异常");
        }
    }

    /**
     * finally 中自己负责异常的捕获和处理
     */
    public static void right1() {
        try {
            log.info("try");
            throw new RuntimeException("try");
        } finally {
            log.info("finally");
            try {
                throw new RuntimeException("finally");
            } catch (Exception ex) {
                log.error("finally", ex);
            }
        }
    }

    /**
     * 把 try 中的异常作为主异常抛出，使用 addSuppressed 方法把 finally 中的异常附加到主异常上
     * 可以实现抛出finally 不覆盖try中的异常
     * @throws Exception
     */
    public static void right2() throws Exception {
        Exception e = null;
        try {
            log.info("try");
            throw new RuntimeException("try");
        } catch (Exception ex) {
            e = ex;
        } finally {
            log.info("finally");
            try {
                throw new RuntimeException("finally");
            } catch (Exception ex) {
                if (e!= null) {
                    e.addSuppressed(ex);
                } else {
                    e = ex;
                }
            }
        }
        throw e;
    }

    /**
     * 使用try -with-resources 实现finally中的异常不覆盖主异常
     */
    public void right3() throws Exception {
        try(ExceptionBug exceptionBug = new ExceptionBug()) {
            exceptionBug.read();
        }
    }

}
